package com.isae.chattingapp;

import org.jivesoftware.smack.XMPPConnection;

import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.view.View;
import android.widget.EditText;

public class SignInActivity extends Activity {
	
	public XMPPConnection XmppConnectionSignIn;
	SharedPreferences sharedPref;
	AlertClass alert;
	Context SignInContext;
	EditText EditTextUsername;
	EditText EditTextPassword;
	String username;
	String password;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_sign_in);
		alert = new AlertClass(this);
		SignInContext = this;
		this.XmppConnectionSignIn = XMPPLogic.getInstance().getConnection();
		EditTextUsername = (EditText) findViewById(R.id.usernameIn);
		EditTextPassword = (EditText) findViewById(R.id.passwordIn);
	}
	
	public void SignIn(View view){
		username = EditTextUsername.getText().toString();
		password = EditTextPassword.getText().toString();
		
		if (username.length() == 0 || password.length() == 0){
			alert.display_alert(getString(R.string.AllFields));
			return;
		}

//		AccountManager am = new AccountManager(XmppConnectionSignIn);
//		//Verifying if the username does not exists
//		if (am.getAccountAttribute(username) == null) {
//			alert.display_alert("l'utilisateur "+username+" est inconnu");
//			return;
//		}
		XMPPLogic.getInstance().setConnection(XmppConnectionSignIn);
		Login l = new Login(new  CallbackConnect() {public void run(XMPPConnection result){
			XmppConnectionSignIn = result;
			if (XmppConnectionSignIn.getUser() == null) {
			  	alert.display_alert(getString(R.string.User)+ " "+username+" "+getString(R.string.With)+" "+getString(R.string.password)+" "+getString(R.string.Unknown));
			  	EditTextUsername.setText("");
			  	EditTextPassword.setText("");
			  	EditTextUsername.requestFocus();
	  			return;
	  		}else{
	  			sharedPref = getSharedPreferences("CREDENTIALS",Context.MODE_PRIVATE);
	  			SharedPreferences.Editor editor = sharedPref.edit();
	  			editor.putString("username", username);
	  			editor.putString("password", password);
	  			editor.commit();	  			
	  			
	  			XMPPLogic.getInstance().setConnection(XmppConnectionSignIn);
	  			Intent main = new Intent(SignInContext, ListRosters.class);
	  	    	startActivity(main);
	  			finish();
	  		}
		}}, SignInContext, username, password);
		l.execute();
	}	
	
	public void GoToSignUp(View view){
		Intent signup = new Intent(this,SignUpActivity.class);
    	startActivity(signup);
	}
}
